package org.stvd.controller.admin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.cache.EHCacheUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 系统缓存-控制类
 * @author houzx
 */
@Api(tags="系统缓存接口类")
@Controller
@RequestMapping("/admin/cache")
public class EHCacheController extends BaseController{
    /*
     * 获取cache keys信息
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map<String, Object> loadCacheInfo(ModelMap map,String cacheName, int pageNo, int pageSize){
        EHCacheUtil ehCacheUtil = new EHCacheUtil() ;
        if(cacheName != null){
            ehCacheUtil.initCache(cacheName);
        }
        List list = ehCacheUtil.getKeys();
        int recordCount = list.size();
        Map<String, Object> gridData = new HashMap<String, Object>();
        gridData.put("pageCount", (int) Math.ceil(recordCount * 1d / pageSize));
        gridData.put("pageIndex", (int) Math.floor((pageNo-1) * pageSize * 1d / pageSize) + 1);
        if ((int)gridData.get("pageCount") > 0 && (int)gridData.get("pageCount") < (int)gridData.get("pageIndex")) {
            gridData.put("pageIndex",(int)gridData.get("pageIndex") - 1);
        }
        gridData.put("total", recordCount);  
        
        int i=0;
        int start = (pageNo - 1) * pageSize;
        int end = (pageNo * pageSize)>recordCount?recordCount:(pageNo * pageSize);
        List rows = new ArrayList();
        
        for(Object key : list){
            if(i >= start && i < end){
                Map<String, Object> row = new HashMap<String, Object>();
                row.put("key", key);
                row.put("value", ehCacheUtil.get(key));
                rows.add(row);
            }
        }
        gridData.put("rows", rows);
        map.put("caches",ehCacheUtil.getAllCaches());
        map.put("queryResult",gridData);
        map.put("cacheName", cacheName);
        return gridData;
    }
    
    /**
     * @Description: 系统缓存管理
     * @param cacheName
     * @return
     */
    @ApiIgnore
    @RequestMapping(value="management")
    public String onPageLoadSessionManagement(String cacheName){
        if(cacheName == null){
            cacheName = "adminCache";
        }
        loadCacheInfo(map, cacheName, pageNo, pageSize);
        return "/admin/cache/EHCacheManagement.html";
    }

    /**
     * @Description: 清除缓存
     * @param cacheName
     * @param key
     * @return
     */
    @ApiOperation("清除缓存信息")
    @Log(title = "清除缓存信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onDelete(String cacheName,String key) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            EHCacheUtil ehCacheUtil = new EHCacheUtil() ;
            if(cacheName != null){
                ehCacheUtil.initCache(cacheName);
            }
            ehCacheUtil.remove(key);
            result.setMsg("缓存‘" + key + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除缓存" + key + "失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * @Description: 清空全部缓存
     * @param cacheName
     * @return
     */
    @ApiOperation("清除全部缓存")
    @Log(title = "清除全部缓存", businessType = BusinessType.CLEAN)
    @PostMapping(value = "clear")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onClear(String cacheName) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            EHCacheUtil ehCacheUtil = new EHCacheUtil() ;
            if(cacheName != null){
                ehCacheUtil.initCache(cacheName);
            }
            ehCacheUtil.removeAllKey();
            result.setMsg("缓存‘" + cacheName + "’清空成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("清空缓存" + cacheName + "失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
}




